const defaultState = {
  list: [
    { name: "sdfdasfds", age: 1, address: "4455445", key: 1 },
    { name: "sdfdsafds", age: 12, address: "fdgdfsgdfsg", key: 2 },
    { name: "sadfdasfdas", age: 152, address: "dfgdfsgdfsg", key: 3 },
    { name: "sdafdasfdsaf", age: 1552, address: "gfdfsgdfsg", key: 4 },
  ],
  status: 0,
  visible: false,
};
const reducer = (state = defaultState, action) => {
  switch (action.type) {
    case "add":
      return {
        ...state,
        list: [...state.list, { ...action.task, key: +new Date() }],
      };
    case "remove":
      return {
        ...state,
        list: state.list.filter((item) => item.key !== action.task),
      };
    case "updata":
      let newList = [...state.list]; //做一个浅拷贝
      let updataindex = state.list.findIndex(
        (item) => item.key === state.status
      ); //用key寻找索引

      newList.splice(updataindex, 1, {
        ...action.task,
        key: state.status,
      });
      return {
        ...state,
        list: newList,
      };
    //弹出框展示
    case "changeVisible":
      return {
        ...state,
        visible: !state.visible,
      };
    //判断添加更新事件
    case "changeStatus":
      console.log(action.task);
      return {
        ...state,
        status: action.task,
      };
    case "up":
      let upList = [...state.list]; //做一个浅拷贝
      let upindex = upList.indexOf(action.task); //寻找做修改值的索引
      let update = upList[upindex - 1]; //需要替换的值
      upList[upindex] = update; //替换赋值
      upList[upindex - 1] = action.task; //替换赋值
      return {
        ...state,
        list: upList,
      };
    case "down":
      let downList = [...state.list]; //做一个浅拷贝
      let dowmindex = downList.indexOf(action.task); //寻找做修改值的索引
      let downDate = downList[dowmindex + 1]; //需要替换的值
      downList[dowmindex + 1] = action.task; //替换赋值
      downList[dowmindex] = downDate; //替换赋值
      return {
        ...state,
        list: downList,
      };
    default:
      return state;
  }
};
export default reducer;
